<template>
    <navbar :showLeft="true" title="AI模拟面试" @leftClick="handleBack"></navbar>
    <view class="header" :style="{paddingTop: appInfoStore.getInfo().navBarHeight + 2*appInfoStore.getInfo().statusBar + 'px'}"></view>

    <view class="fixed-container">
      <view class="interview-question-page">
        <image
          class="background-image"
          src="/static/images/person2.png"
          mode="aspectFill"
        />

        <view class="content-wrapper">
          <!-- 模拟面试标题 -->
          <view class="interview-tag">模拟面试：{{ position }}</view>

          <view v-if="!isStartInterview" class="start-container">
            <view class="tips-card">
              <text class="tips-text">准备好开始面试了吗？</text>
              <text class="sub-text">点击下方按钮开始模拟面试</text>
            </view>

            <!-- 开始按钮 -->
            <button
              class="start-button"
              hover-class="button-hover"
              @click="startInterview"
            >
              我准备好了
            </button>
          </view>

          <view v-if="isStartInterview">
            <!-- 题目区域 -->
            <view class="question-box">
              <view class="question-header">
                <text class="question-title">题目</text>
                <text class="question-index">{{ currentQuestion+1 }}/{{ totalQuestions }}</text>
              </view>
              <view class="question-content">
                <text class="subtitle">题目</text>
                <text class="question-text">{{ questionData.questionContent||questionData.question }}</text>
                <text class="subtitle">评价标准</text>
                <text class="evaluation-text">{{ questionData.evaluationContent||questionData.evaluation }}</text>
              </view>
            </view>

            <!-- 倒计时显示 -->
            <view class="countdown-display">
              剩余时间: {{ countdown }}:{{ formattedSeconds }}
            </view>

            <view class="btn-bottom">
              <!-- 录音按钮 -->
            <button
              class="record-button"
              @touchstart="handleStartRecording"
              @touchend="handleStopRecording"
              @touchcancel="handleStopRecording"
              :disabled="isUploading"
            >
              {{ isRecording ? '松开结束' : '按住录音' }}
            </button>

            <!-- 回答完毕按钮 -->
            <button
              class="finish-btn"
              @click="handleFinishAnswer"
              :disabled="isUploading || isRecording"
            >
              {{ isUploading ? '上传中...' : '回答完毕' }}
            </button>
            </view>
          </view>
        </view>
      </view>
    </view>
</template>

<script setup>
import { ref, computed, onMounted, getCurrentInstance, onBeforeUnmount } from 'vue'
const appInfoStore = useAppInfoStore();
import { useAppInfoStore } from "@/stores/appInfo";
import { onShow, onLoad, onReady } from '@dcloudio/uni-app';
const { proxy } = getCurrentInstance();

// 面试状态
const isStartInterview = ref(false);
const isUploading = ref(false);
const isRecording = ref(false);

// 倒计时数据
const countdown = ref(1);
const seconds = ref(0);
const timer = ref(null);
let lastUpdateTime = 0;

// 格式化秒数显示
const formattedSeconds = computed(() => {
  return seconds.value < 10 ? `0${seconds.value}` : seconds.value;
});

// 倒计时函数
const startCountdown = () => {
  if (timer.value) clearInterval(timer.value);

  countdown.value = 1;
  seconds.value = 0;
  lastUpdateTime = Date.now();

  timer.value = setInterval(() => {
    const now = Date.now();
    const delta = now - lastUpdateTime;

    if (delta >= 1000) {
      lastUpdateTime = now - (delta % 1000);

      if (seconds.value > 0) {
        seconds.value--;
      } else {
        if (countdown.value > 0) {
          countdown.value--;
          seconds.value = 59;
        } else {
          clearInterval(timer.value);
          timer.value = null;
          handleTimeUp();
        }
      }
    }
  }, 200);
};

// 播放音频
// 修改后的 playAudio 函数
const playAudio = (file) => {
    console.log('播放音频文件:', file);

    if (!file) {
        console.error('音频文件路径为空');
        return Promise.resolve(); // 返回一个已解决的Promise保持链式调用
    }

    return new Promise((resolve) => {
        // 先停止之前的音频
        innerAudioContext.stop();

        // 设置音频源
        innerAudioContext.src = file;

        innerAudioContext.onPlay(() => {
            console.log('音频开始播放');
            resolve();
        });

        innerAudioContext.onError((res) => {
            console.error('音频播放错误:', res);
            uni.showToast({
                title: '音频播放失败',
                icon: 'none'
            });
            resolve(); // 即使出错也resolve
        });

        // 播放音频
        try {
            innerAudioContext.play();
        } catch (err) {
            console.error('播放音频失败:', err);
            uni.showToast({
                title: '播放失败，请检查网络或文件路径',
                icon: 'none'
            });
            resolve();
        }
    });
};

// 倒计时结束处理
const handleTimeUp = async () => {
  if (isRecording.value) {
    await stopRecording();
  }

  if (currentQuestion.value + 1 < totalQuestions.value) {
    await goToNextQuestion();
  } else {
    await submitMyAnswer();
  }
};

// 录音管理
const recorderManager = uni.getRecorderManager();
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = false;
const voicePath = ref("");

// 初始化录音监听
const initRecorder = () => {
  recorderManager.onStop((res) => {
    console.log('录音停止', res);
    voicePath.value = res.tempFilePath;
    uploadFile(voicePath.value, res.duration);
  });
};

// 开始录音
const startRecording = () => {
  isRecording.value = true;
  recorderManager.start({
    format: 'mp3',
    duration: 60000,
    sampleRate: 44100,
    numberOfChannels: 1,
    encodeBitRate: 192000,
    success() {
      console.log('录音启动成功');
    },
    fail(err) {
      console.error('录音启动失败:', err);
      isRecording.value = false;
      uni.showToast({
        title: '录音启动失败',
        icon: 'none'
      });
    }
  });
};

// 停止录音
const stopRecording = () => {
  return new Promise((resolve) => {
    isRecording.value = false;
    recorderManager.stop();
    resolve();
  });
};

// 处理开始录音
const handleStartRecording = () => {
  if (!isRecording.value) {
    startRecording();
  }
};

// 处理停止录音
const handleStopRecording = () => {
  if (isRecording.value) {
    stopRecording();
  }
};

// 上传音频文件
const uploadFile = async (tempFilePath, duration) => {
  isUploading.value = true;

  try {
    uni.showLoading({
      title: '音频上传中...',
      mask: true
    });

    const uploadRes = await new Promise((resolve, reject) => {
      uni.uploadFile({
        url: proxy.Api.domain + proxy.Api.saveAudio,
        header: {
          'token': uni.getStorageSync('token') || '',
          'Content-Type': 'multipart/form-data'
        },
        filePath: tempFilePath,
        name: 'file',
        formData: { duration },
        success: resolve,
        fail: reject
      });
    });

    const responseData = JSON.parse(uploadRes.data);
    questionList.value[currentQuestion.value].userAnswer = responseData.data?.sisText || '';
    questionList.value[currentQuestion.value].answerAudioId = responseData.data?.audioId || '';

    uni.showToast({
      title: '保存成功',
      icon: 'success'
    });

    return true;
  } catch (err) {
    console.error("上传失败:", err);
    uni.showToast({
      title: '上传失败，请重试',
      icon: 'none'
    });
    return false;
  } finally {
    uni.hideLoading();
    isUploading.value = false;
  }
};

// 进入下一题
const goToNextQuestion = async () => {
  currentQuestion.value++;
  questionData.value = questionList.value[currentQuestion.value];
  countdown.value = 1;
  seconds.value = 0;
  await playAudio("http://localhost:9096"+questionData.value.filePath);
};

// 回答完毕按钮事件
const handleFinishAnswer = async () => {
  if (isUploading.value || isRecording.value) return;

  if (isRecording.value) {
    await stopRecording();
  }

  if (currentQuestion.value + 1 < totalQuestions.value) {
    const uploadSuccess = await new Promise(resolve => {
      const checkUpload = setInterval(() => {
        if (!isUploading.value) {
          clearInterval(checkUpload);
          resolve(true);
        }
      }, 500);
    });

    if (uploadSuccess) {
      await goToNextQuestion();
    }
  } else {
    await submitMyAnswer();
  }
};

// 提交报告
const submitMyAnswer = async () => {
  uni.showLoading({
    title: '报告生成中...',
    mask: true
  });

  try {
    const result = await proxy.Request({
      url: proxy.Api.saveMyAnswer,
      showLoading: false,
      data: questionList.value,
      dataType: "json"
    });

    if (!result) {
      throw new Error('无效的响应数据');
    }

    uni.showToast({
      title: '面试完成',
      icon: 'success',
      duration: 2000
    });

    setTimeout(() => {
      uni.navigateTo({
        url: `/pages/report/InterviewReport?interviewId=${result}`
      });
    }, 2000);
  } catch (error) {
    console.error('提交失败:', error);
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 初始化
onReady(() => {
  initRecorder();
});

onBeforeUnmount(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
  if (isRecording.value) {
    recorderManager.stop();
  }
});

// uni-app返回上一页
const handleBack = () => {
  uni.navigateBack({
    delta: 1
  });
};

const currentCategoryInfo = ref({});
const position = ref('销售');
const currentQuestion = ref(0);
const totalQuestions = ref(5);
const questionList = ref([{}]);
const questionData = ref({
  questionContent: "请举例说明你成功开拓新客户的经历及方法。",
  evaluationContent: "清晰阐述过程、方法及成果，体现开拓能力。",
});

// 初始化题目
const initQuestion = async (categoryId) => {
  try {
    const result = await proxy.Request({
      url: proxy.Api.addAppInterview,
      showLoading: true,
      data: { type: categoryId },
      dataType: "json"
    });

    if (!result) {
      throw new Error('无效的响应数据');
    }

    questionList.value = result;
    totalQuestions.value = result.length;
    questionData.value = questionList.value[currentQuestion.value];
    await playAudio("http://localhost:9096"+questionData.value.filePath);
  } catch (error) {
    console.error('初始化题目失败:', error);
    uni.showToast({
      title: '加载题目失败',
      icon: 'none'
    });
  }
};

onLoad((options) => {
  currentCategoryInfo.value.categoryId = decodeURIComponent(options.categoryId);
  currentCategoryInfo.value.categoryName = decodeURIComponent(options.categoryName);
  position.value = currentCategoryInfo.value.categoryName;
});

const startInterview = async() => {
  isStartInterview.value = true;
 await initQuestion(currentCategoryInfo.value.categoryId); // 等待初始化完成
  startCountdown();
};
</script>

<style scoped>
.fixed-container {
  position: relative;
  top: 0;
  left: 0;
  width: 100%;
  height: 85vh;
  overflow: hidden;
}
.interview-question-page {
  position: relative;
  overflow: hidden;
  height: 100%;
}
.background-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}
.nav-left {
  position: absolute;
  left: 15px;
}

.back-icon {
  font-size: 20px;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

.content-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  box-sizing: border-box;
  min-height: 100vh;
  background-color: rgba(255, 255, 255, 0.20);
}

.interview-tag {
  margin-top: 20px;
  padding: 12px 24px;
  font-size: 16px;
  background: rgba(255, 255, 255, 0.5);
  color: black;
  border-radius: 25px;
  width: auto;
  min-width: 200px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.question-box {
  width: 100%;
  background: rgba(255, 255, 255, 0.6);
  border-radius: 10px;
  padding: 15px;
  box-sizing: border-box;
  margin: 280px auto 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.question-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.question-index {
  font-size: 14px;
  color: black;
}

.question-content {
  line-height: 1.6;
}

.subtitle {
  display: block;
  font-size: 15px;
  font-weight: bold;
  color: black;
  margin-bottom: 5px;
}

.question-text,
.evaluation-text {
  display: block;
  font-size: 14px;
  color: black;
  margin-bottom: 15px;
}

.countdown-display {
  margin-left: 15px;
  margin-bottom: 15px;
  margin-top: 20px;
  font-size: 16px;
  color: #333;
  font-weight: bold;
}

.record-button {
  background: linear-gradient(135deg, #df5e5e, #d63434);
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  border: none;
  border-radius: 22px;
  height: 44px;
  line-height: 44px;
  width: 170px;
  cursor: pointer;
  box-shadow: 0 4px 8px rgba(255, 82, 82, 0.3);
  transition: all 0.3s ease;
}

.finish-btn {
  background: linear-gradient(135deg, #6083db, #0b3591);
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  border: none;
  border-radius: 22px;
  margin-left: 10px;
  height: 44px;
  line-height: 44px;
  width: 170px;
  cursor: pointer;
  box-shadow: 0 4px 8px rgba(96, 131, 219, 0.3);
  transition: all 0.3s ease;
}

/* 容器样式 */
.start-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 70vh;
  padding: 0 40rpx;
}

/* 提示卡片样式 */
.tips-card {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding: 40rpx;
  margin-top: 310px;
  margin-bottom: 60rpx;
  width: 100%;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.08);
  text-align: center;
}

.tips-text {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
  display: block;
  margin-bottom: 16rpx;
}

.sub-text {
  font-size: 28rpx;
  color: #666666;
  display: block;
}

/* 按钮样式 */
.start-button {
  width: 100%;
  height: 96rpx;
  line-height: 96rpx;
  border-radius: 48rpx;
  background: linear-gradient(135deg, #1976D2, #2196F3);
  color: white;
  font-size: 32rpx;
  font-weight: 500;
  border: none;
  box-shadow: 0 8rpx 20rpx rgba(25, 118, 210, 0.3);
  transition: all 0.3s ease;
}

.button-hover {
  opacity: 0.9;
  transform: translateY(-2rpx);
  box-shadow: 0 12rpx 24rpx rgba(25, 118, 210, 0.4);
}

.btn-bottom{
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 响应式调整 */
@media (min-width: 768px) {
  .start-container {
    max-width: 500rpx;
    margin: 0 auto;
  }
}
</style>